package cn.agiledata.bank.information.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.common.dao.AccountTemplate;
import cn.agiledata.bank.common.dao.SysTemplate;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.MD5;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.hibernateBean.MobileChargeRecord;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.SysParameter;
import cn.agiledata.bank.information.service.MobileChargeService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

/**
 * 手机充值Action
 * 
 * @author 马贤波
 *
 */
public class MobileChargeAction extends IPBBaseAction {
	
	
	public int hasAccessPermission(int arg0, HttpServletRequest arg1) throws IPBException {
		return 1;
	}
	
	public MobileChargeService getChargeService() {
		return (MobileChargeService)IPBAppFactory.getObj("mobileChargeService");
	}

	/**
	 * 转向到充值选择页面
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward chargeSelect(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
		// 查询当前充值实际收费金额
		getChargetRealAmt(request);
		
		return mapping.findForward("select");
	}

	/**
	 * 查询取得充值实际金额
	 * 
	 * @param request
	 */
	private void getChargetRealAmt(HttpServletRequest request) {
		SysTemplate sysTemplate = (SysTemplate) IPBAppFactory
				.getObj("sysTemplate");
		SysParameter spCharge50 = sysTemplate.getParamByType(Constant.SYS_PARAM_MOBILE_CHARGE_50);
		SysParameter spCharge100 = sysTemplate.getParamByType(Constant.SYS_PARAM_MOBILE_CHARGE_100);
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		if (accountId != 0) {
			spCharge50 = sysTemplate.getParamByType(Constant.SYS_PARAM_MOBILE_CHARGE_UU_50);
			spCharge100 = sysTemplate.getParamByType(Constant.SYS_PARAM_MOBILE_CHARGE_UU_100);
		}
		request.setAttribute("charge50Value", spCharge50.getParmValue());
		request.setAttribute("charge100Value", spCharge100.getParmValue());
	}
	
	/**
	 * 手机充值支付
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward chargePay(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
		HttpSession session=request.getSession();
		String strMobileNum="";
		String strChargeType="";
		// 取得页面输入内容
		if(StringUtils.isNotBlank(request.getParameter("mobileNum")))
		strMobileNum = request.getParameter("mobileNum").trim();
		else 
		strMobileNum =session.getAttribute("mobileNum").toString();
		if(StringUtils.isNotBlank(request.getParameter("chargeType")))
		strChargeType = request.getParameter("chargeType").trim();
		else 
		strChargeType =session.getAttribute("chargeType").toString();
		
		
		// 验证手机
		if(!validateMoibleNum(strMobileNum)) {
			request.setAttribute("errMsg", "请输入正确的手机号码！");
			// 查询当前充值实际收费金额
			getChargetRealAmt(request);
			return mapping.findForward("error");
		}
		
		// 验证充值类型
		if(Integer.parseInt(strChargeType) != Constant.MOBILE_CHARGE_TYPE_50
				&& Integer.parseInt(strChargeType) != Constant.MOBILE_CHARGE_TYPE_100) {
			request.setAttribute("errMsg", "错误的充值类型!");
			// 查询当前充值实际收费金额
			getChargetRealAmt(request);
			return mapping.findForward("error");
		}
		
		// 取得充值类型实际消费金额
		SysParameter param = getChargeValue(strChargeType, request);
		String strRealAmt = param.getParmValue();
		
		session.setAttribute("mobileNum", strMobileNum);
		session.setAttribute("chargeValue", strRealAmt);
		session.setAttribute("chargeType", strChargeType);
		boolean isAllow=true;
		AccountTemplate at = (AccountTemplate) IPBAppFactory
		.getObj("accountTemplate");
		AccountSummary accountSummary=WeatherUtil.getLoingInfoFromSession(request);
		List sblist=null;
		if(accountSummary==null)
			isAllow=false;
		if (isAllow) {
		 sblist=accountSummary.getSubAccountList();
		 if (sblist==null||sblist.size()==0)
			isAllow=false;
		}
		if (isAllow) {
			SubAccount sa=(SubAccount)sblist.get(0);
			if ("true".equals(at.authentication(sa.getId().toString())))//未进行实名认证
				isAllow=false;
		}
		if(!isAllow){
			session.setAttribute("thesign", 1);
			return mapping.findForward("tologin");
		}
		// 查询当前充值实际收费金额
		getChargetRealAmt(request);
		
		
	
		return mapping.findForward("pay");
	}

	/**
	 * 验证手机号码
	 * 
	 * @param strMobileNum
	 * @return
	 * @throws MalformedPatternException
	 */
	private boolean validateMoibleNum(String strMobileNum) throws MalformedPatternException {
		// 验证手机号码
		String strRegExp1 = "13[4-9]{1}\\d{8}";
		String strRegExp2 = "150\\d{8}";
		String strRegExp3 = "15[6-9]{1}\\d{8}";
		
		PatternCompiler compiler = new Perl5Compiler();
		Pattern pattern1 = compiler.compile(strRegExp1);
		Pattern pattern2 = compiler.compile(strRegExp2);
		Pattern pattern3 = compiler.compile(strRegExp3);
		
		PatternMatcher matcher = new Perl5Matcher();
		if(strMobileNum.length() == 0 
				|| (!matcher.contains(strMobileNum, pattern1)
				&& !matcher.contains(strMobileNum, pattern2)
				&& !matcher.contains(strMobileNum, pattern3))) {
			return false;
		}
		
		return true;
	}

	/**
	 * 根据充值类型取得实际金额
	 * 
	 * @param strChargeType
	 * @return
	 */
	private SysParameter getChargeValue(String strChargeType, HttpServletRequest request) {
		SysTemplate sysTemplate = (SysTemplate) IPBAppFactory
				.getObj("sysTemplate");
		String strParamCharge = null;
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		if(Integer.parseInt(strChargeType) == Constant.MOBILE_CHARGE_TYPE_50) {
			strParamCharge = Constant.SYS_PARAM_MOBILE_CHARGE_50;
			if (accountId != 0) strParamCharge = Constant.SYS_PARAM_MOBILE_CHARGE_UU_50;
		}
		if(Integer.parseInt(strChargeType) == Constant.MOBILE_CHARGE_TYPE_100) {
			strParamCharge = Constant.SYS_PARAM_MOBILE_CHARGE_100;
			if (accountId != 0) strParamCharge = Constant.SYS_PARAM_MOBILE_CHARGE_UU_100;
		}
		SysParameter param = sysTemplate.getParamByType(strParamCharge);
		
		
		return param;
	}
	
	/**
	 * 充值内容提交
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward chargeSubmit(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {

		// 取得页面输入内容
		String strMobileNum = request.getParameter("mobileNum").trim();
		String strChargeType = request.getParameter("chargeType").trim();
		String strEmail = request.getParameter("email").trim();
		
		if(!validateMoibleNum(strMobileNum)) {
			return null;
		}

		// 取得充值类型实际消费金额
		SysParameter param = getChargeValue(strChargeType, request);
		String strRealAmt = param.getParmValue();

		// 生成充值记录
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		SysTemplate sysTemplate = (SysTemplate) IPBAppFactory
				.getObj("sysTemplate");
		SysParameter chargeTimes = sysTemplate.getParamByType(Constant.SYS_PARAM_MOBILE_TIMES_1DAY);
		// 默认1天只能充值一次
		int tradTime = 1;
		try {
			tradTime = Integer.parseInt(chargeTimes.getParmValue().trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
//		if (accountId != 0) {
//			if (!getChargeService().isLegalCharge(new Long(accountId), tradTime)){
//				request.setAttribute("errMsg", "同一账号每天仅限充" + tradTime +"次，您今天已充值过，请明天再来^_^！");
//				// 查询当前充值实际收费金额
//				getChargetRealAmt(request);
//				return mapping.findForward("error");
//			}
//		}
		MobileChargeRecord record = getChargeService().createRecord(
				strMobileNum, strChargeType, strEmail, accountId);

		// 设置商户接口需要用到的参数
		request.setAttribute("merchantId", Constant.MOBILE_CHARGE_ACCOUNTID);
		request.setAttribute("merchantUrl", WebUtil.getRoot(request) + "/page/information/mobilePayReponse.do");
		request.setAttribute("responseMode", "3");
		request.setAttribute("orderId", record.getRecordNo());
		request.setAttribute("amount", strRealAmt);
		request.setAttribute("currencyType", "CNY");
		request.setAttribute("assuredPay", "false");
		String now = DateUtil.date2String(new Date(), "yyyyMMddHHmmss");
		request.setAttribute("time", now);
		AccountSummary accountSummary=WeatherUtil.getLoingInfoFromSession(request);
		long theId=accountSummary.getAccountId();
		request.setAttribute("theId",theId);
		String mac = "merchantId=" + Constant.MOBILE_CHARGE_ACCOUNTID
				+ "&merchantUrl=" + WebUtil.getRoot(request)+ "/page/information/mobilePayReponse.do" 
				+ "&responseMode=3"
				+ "&orderId=" + record.getRecordNo() 
				+ "&currencyType=CNY"
				+ "&amount=" + strRealAmt 
				+ "&assuredPay=false" 
				+ "&time="+ now 
				+ "&remark=" 
				+"&theId="+theId
				+ "&merchantKey=" + Constant.MOBILE_CHARGE_KEY;
		mac = new MD5().getMD5ofStr(mac);
		request.setAttribute("mac", mac);

		
		String flag = request.getParameter("flag");
		if (StringUtils.isNotBlank(flag)) request.getSession().setAttribute("flag", "barCode");
		HttpSession session=request.getSession();
		session.removeAttribute("mobileNum");
		session.removeAttribute("chargeValue");
		session.removeAttribute("chargeType");
		return mapping.findForward("submit");
	}
	
	/**
	 * 支付结果响应
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward payResponse(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
		
		String transId = request.getParameter("unsTransId");	// 交易编号
		String recordNo = request.getParameter("orderId");		// 充值记录订单号
		
		if (Constant.RETURNSUCCESS.equals(request.getParameter("returnCode"))) {
			// 支付成功
			// 进行充值确认
			MobileChargeRecord record = null;
			synchronized (this) {
				record = getChargeService().recordPayConfirm(recordNo, transId);
			}
			
			request.setAttribute("record", record);
			request.setAttribute("flag", "success");
		} else {
			MobileChargeRecord record = getChargeService().getRecordByNo(recordNo);
			request.setAttribute("record", record);
			request.setAttribute("flag", "error");
		}
	
		return mapping.findForward("result");
	}
}
